﻿import QtQuick 2.0

Item {
    id: delegate
    width: imgWidth
    height: imgHeight
    clip: true
    smooth: true

    property alias rotation: rotation
    property alias img: name
    property alias txt: txt
    property alias mouse: mouse
    property int myIndex: 0
    property real lastAngle: 0

    transform: Rotation{
        id: rotation
        origin.x: delegate.width/2
        origin.y: delegate.height/2
        axis.x: 0
        axis.y: 0
        axis.z: 1
        angle: 0
    }

    onVisibleChanged: {
        if(delegate.visible){
            rotation.angle = lastAngle
        }
    }

    Rectangle{
        anchors.fill: parent
        color: "yellow"
        opacity: 0
    }

    Image {
        id: name
        x: -Math.floor(myIndex%type) * imgWidth
        y: -Math.floor(myIndex/type) * imgHeight
        source: ""
        smooth: true
    }

    Text {
        id: txt
        anchors.centerIn: parent
        text: myIndex
        font.pixelSize: 40
        color: "red"
        opacity: 0
    }

    MouseArea{
        id: mouse
        anchors.fill: parent
        drag.target: parent
        enabled: true
        visible: enabled

        onPressed: {
            lastAngle = rotation.angle
//            rotation.angle = 0
            currentDrag = myIndex
            startX = delegate.x
            startY = delegate.y

            delegate.z = 1

            lastIndex = -1
        }

        onReleased: {
            calcEnd(delegate.x + delegate.width/2,delegate.y + delegate.height/2)
            delegate.z = 0
            if(delegate.visible){
                rotation.angle = lastAngle
            }
        }

        onPositionChanged: {
            calcCenter(delegate.x + delegate.width/2,delegate.y + delegate.height/2)
        }
    }
}
